import { defineStore } from "pinia";

const defaultStore = {
    hierarchy: {
        dragging: false,
        width: 300,
        expand: true
    },
    attr: {
        dragging: false,
        width: 300,
        expand: true
    },
    shape: {
        visible: false
    },
    coordinate: {
        visible: true,
        data: {
            x: 0,
            y: 0,
            z: 0
        }
    },
    bodies: {
        visible: false
    }
};

export const useLayout = defineStore("layout", {
    state: () => defaultStore,

    getters: {},
    actions: {
        startHierarchyDrag(cx: number) {
            this.hierarchy.dragging = true;
            let originWidth = this.hierarchy.width;
            const onMove = (e: MouseEvent) => {
                let w = originWidth + (e.clientX - cx);
                if (w < 80) {
                    w = 80;
                }
                this.hierarchy.width = w;
            }

            const onUp = () => {
                window.removeEventListener("mousemove", onMove);
                window.removeEventListener("mouseup", onUp);
            }
            window.addEventListener("mousemove", onMove);
            window.addEventListener("mouseup", onUp);
        },
        startAttrDrag(cx: number) {
            this.attr.dragging = true;
            let originWidth = this.attr.width;
            const onMove = (e: MouseEvent) => {
                let w = originWidth - (e.clientX - cx);
                if (w < 80) {
                    w = 80;
                }
                this.attr.width = w;
            }

            const onUp = () => {
                window.removeEventListener("mousemove", onMove);
                window.removeEventListener("mouseup", onUp);
            }
            window.addEventListener("mousemove", onMove);
            window.addEventListener("mouseup", onUp);
        },
        showShape(val: boolean) {
            this.shape.visible = val;
        },
        showBodies(val: boolean) {
            this.bodies.visible = val;
        },
        showCoordinate(val: boolean) {
            this.coordinate.visible = val;
        },
        changeCoordinateData(val: any) {
            this.coordinate.data = val;
        },
        toggleHierarchyExpand(){
            this.hierarchy.expand = !this.hierarchy.expand;
        },
        toggleAttrExpand(){
            this.attr.expand = !this.attr.expand;
        }
    }
});
